import React, { useState, useEffect, useMemo } from 'react'
import { NavBar } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { Button } from 'react-vant'
import Cartlist from './cartlist/Cartlist'
import { useSelector } from 'react-redux'
import { cartList, checkAll } from '../../models'
import { SubmitBar, Checkbox } from 'react-vant';
import Recommendlist from './recommendlist/Recommendlist'

export default function Cart() {
  const navigate = useNavigate()
  let [cartlist, setCartlist] = useState([])
  let [type, setType] = useState(false)
  const { userId } = useSelector(state => state.user)
  useEffect(() => {
    getCartList()
  }, [])
  const price = useMemo(() => {
    return cartlist.length > 0 ? cartlist.map(item => item.originprice * item.num).reduce((a, b) => a + b) : 0
  }, [cartlist])
  const back = () => {
    navigate(-1)
  }
  const getCartList = () => {
    cartList(userId).then(res => {
      console.log(res);
      if (res.data) {
        setCartlist(res.data)
        let bool = res.data.every(item => item.flag)
        setType(bool)
      } else {
        setCartlist([])
      }
    })
  }
  const changeAll = () => {
    checkAll({
      userid: userId,
      type: !type
    }).then(res => {
      console.log(res)
      getCartList()
      setType(!type)
    })
  }
  return (
    <div>
      <NavBar style={{ backgroundColor: '#fff' }} back='返回' onBack={back}>
        购物车({cartlist.length})
      </NavBar>
      <div style={{ padding: '5px' }}>
        {
          cartlist.length === 0 && <div style={{ textAlign: 'center', marginTop: '50px' }}>
            <img src={require("../../assets/cart.png")} alt="" width='118px' height='168px' />
            <br />
            <Button onClick={() => navigate('/home')} round color='linear-gradient(to right, #ff6034, #ee0a24)' style={{ height: '40px', width: '160px' }}>
              立即购物
            </Button>
          </div>
        }
        {
          cartlist.length > 0 && <Cartlist cartlist={cartlist} getCartList={getCartList} setType={setType} />
        }
      </div>
      <h4>可能你还想要</h4>
      <br />
      <Recommendlist />
      <div className="demo-submit-bar">
        <SubmitBar
          price={price * 100}
          buttonText="提交订单"
          tip={
            <>
              你的收货地址不支持同城送,
              <span style={{ color: '#1989fa' }}>修改地址</span>
            </>
          }
        >
          <Checkbox checked={type} onChange={changeAll}>{type ? '全不选' : '全选'}</Checkbox>
        </SubmitBar>
      </div>
    </div>
  )
}
